import copy

import joblib
from flask import Flask, render_template, request, session, redirect, url_for, jsonify
import pandas as pd
# 加载数据

app = Flask(__name__)#创建Flask类的一个实例
app.secret_key = "DragonFire"  # 这里一定要给定字符串，进行加密 session域

import pymysql
encoder = joblib.load('onehot_encoder.pkl')
# 导入模型
# 加载模型
loaded_model = joblib.load('randomForest.pkl')

# 连接数据库
db = pymysql.connect(host='127.0.0.1', user='root', passwd="123456", db='aqy')
def exec(sql):
    cursor = db.cursor()
    # 执行语句
    cursor.execute(sql)
    return cursor.fetchall()

@app.route("/predict", methods=['POST', 'GET'])
def predict():
    """
    预测后面几5个月
    :return:
    """

    sample = {'tag': '都市;爱情;剧情;生活;当代;内地',
              'creator': '王 欢',
              'contributor': "'江疏影', '杨采钰', '张佳宁', '张慧雯', '李浩菲'",
              'title': '唐人街探案2',
              'year': 2024,
              'month': 3,
              'bossStatus': 'FREE',
              'hot_score': 6008}

    tag = request.form.get('tag')
    creator = request.form.get('creator')
    contributor = request.form.get('contributor')
    title = request.form.get('title')
    year = request.form.get('year')
    month = request.form.get('month')
    boss_status = request.form.get('bossStatus')
    hot_score = request.form.get('hot_score')

    sample = {'tag': tag,
              'creator': creator,
              'contributor': contributor,
              'title': title,
              'year': year,
              'month': month,
              'bossStatus': boss_status,
              'hot_score': hot_score}

    print(sample)
    sample['month'] = int(sample['month'])
    new_samples = [sample]
    key = [sample['month']]
    for i in range(4):
        new_sample = copy.deepcopy(sample)  # 深拷贝原始样本
        new_sample['month'] += i+1
        key.append(new_sample['month'])
        new_samples.append(new_sample)

    # 将单个样本转换为DataFrame
    sample_df = pd.DataFrame(new_samples)

    # 对特征进行预处理，例如独热编码
    sample_encoded = encoder.transform(sample_df)
    res = loaded_model.predict(sample_encoded).tolist()
    print(res, "结果")
    result = []
    result.append(key)
    result.append(res)


    return jsonify({'prediction': result})



@app.route('/')
def hello_world():
    # 总数
    sql = "select sum(year_num) from years"
    all = int (exec(sql)[0][0])
    #sql 语句 年平均热度
    sql = "select year,year_num,avg_hot from  years"
    year = exec(sql)
    print(all, year)

    #月平均热度
    sql = "select month,month_num,avg_hot from month_data"
    month = exec(sql)

    # 演员 收视率 推荐
    sql = "select contributor,contributor,per_avg from contributor order by per_avg desc"
    contributor = exec(sql)


    #地域划分
    sql = "select bossStatus, status, avg_hot from vip_status"
    province = exec(sql)
    data4 = []
    for i in province:
        dic = {}
        dic['name'] = i[0]
        dic['value'] = i[1]
        data4.append(dic)
    print(data4)

    #tag
    sql = "select tag,tag_num,avg_per from tag"
    tags = exec(sql)
    print(tags)

    #所需经验
    sql = "select tag_pcw,pcw_num,per_avg from pcw "
    pcw = exec(sql)

    # 港剧：普通话
    gv = pcw[0][2]
    pv = pcw[1][2]

    # 年份
    years = []
    year_key = []
    for i in year:
        dic = {}
        dic['name'] = i[0]
        dic['value'] = i[2]
        year_key.append(i[0])
        years.append(dic)
    print(years)

    # 月份
    months = []
    for i in month:
        dic = {}
        dic['name'] = i[0]
        dic['value'] = i[2]
        months.append(dic)

    # 演员
    contributor_key = [item[0] for item in contributor]
    contributor_value = [item[2] for item in contributor]




    # return render_template("aqy/index.html",data=data[0],data1=data1[0],data2=data2[0],data3=data3[0],data4=data4,data5=data5[0],data6=data6,data7=data7,data8=job_info)
    return render_template("aqy/index.html", years=years, year_key=year_key, months=months, gv=gv, pv=pv,
                           all= all, ceo=len(tags), contributor_key=contributor_key, contributor_value=contributor_value)




if __name__ == '__main__':
    app.run()
    predict(None)
